/**
 * Copyright 2008 Mathias Doenitz, http://lis.to/
 *
 * This file is part of the lis.to java desktop client. The lis.to java desktop client is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * The lis.to java desktop client is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with the lis.to java desktop client.
 * If not, see http://www.gnu.org/licenses/
 */

package listo.client.model;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import listo.utils.types.Cal;
import listo.utils.types.Copyable;
import listo.utils.types.DateTime;
import org.apache.commons.lang.StringUtils;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * The central user object representing a task.
 */
@XStreamAlias("task")
public class Task extends ModelObject implements Copyable<Task>, Cloneable {
    private static final Cal EMPTY_DUE_DATE_CAL = new Cal().set(2000, 0, 1).set(0, 0, 0, 0);
    private static final DateTime EMPTY_DUE_DATE = EMPTY_DUE_DATE_CAL.getDateTime();

    @XStreamAsAttribute private Boolean completed;
    @XStreamAsAttribute private DateTime due;
    @XStreamAsAttribute private Integer reminder;
    @XStreamAsAttribute private String desc;
    @XStreamAsAttribute private DateTime lastUpdated;

    private String note;

    @XStreamImplicit(itemFieldName = "folder") private Set<ObjectId> folders;

    public boolean isCompleted() {
        return completed != null;
    }

    public void setCompleted(boolean completed) {
        this.completed = completed ? Boolean.TRUE : null;
        markUpdate();
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
        markUpdate();
    }

    public boolean hasDueDate() {
        return due != null && new Cal(due).getDateValue() != Task.EMPTY_DUE_DATE_CAL.getDateValue();
    }

    public boolean hasDueTime() {
        return due != null && new Cal(due).getTimeOfDayValue() != Task.EMPTY_DUE_DATE_CAL.getTimeOfDayValue();
    }

    public boolean hasReminder() {
        return reminder != null;
    }

    public DateTime getDue() {
        return due;
    }

    public void setDue(DateTime due) {
        this.due = EMPTY_DUE_DATE.equals(due) ? null : due;
        markUpdate();
    }

    public void setDueDate(DateTime date) {
        DateTime newDue = null;
        if (date != null) {
            Cal cal = new Cal(date);
            newDue = (due != null ? new Cal(due) : new Cal().beginningOfDay()).
                    set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).getDateTime();
        } else if (due != null) {
            Cal cal = new Cal(due);
            newDue = Task.EMPTY_DUE_DATE_CAL.set(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), 0, 0)
                    .getDateTime();
        }
        setDue(newDue);
    }

    public void setDueTime(DateTime time) {
        DateTime newDue = null;
        if (time != null) {
            // set the time
            // if there is no due date set yet we set either today (if time > now) or tomorrow
            Cal cal = new Cal(time);
            newDue = (due != null ? new Cal(due) : new Cal().add(Calendar.DATE,
                    cal.getTimeOfDayValue() < new Cal().getTimeOfDayValue() ? 1 : 0)).
                    set(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), 0, 0).getDateTime();
        } else if (due != null) {
            // clear the time
            Cal cal = new Cal(due);
            newDue = Task.EMPTY_DUE_DATE_CAL
                    .set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).getDateTime();
        }
        setDue(newDue);
    }

    public Integer getReminder() {
        return reminder;
    }

    public void setReminder(Integer reminder) {
        this.reminder = reminder;
        markUpdate();
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
        markUpdate();
    }

    public DateTime getLastUpdated() {
        return lastUpdated;
    }

    private void markUpdate() {
        lastUpdated = new DateTime();
    }

    public Set<ObjectId> getFolders() {
        return folders;
    }

    public int getFolderCount() {
        return folders != null ? folders.size() : 0;
    }

    public String getFolderIdsString() {
        StringBuilder sb = new StringBuilder();
        if (folders != null) {
            for (ObjectId id : folders) {
                if (sb.length() > 0) sb.append('/');
                sb.append(id);
            }
        }
        return sb.toString();
    }

    public void setFolderIds(ObjectId... folders) {
        this.folders = null;
        if (folders == null) {
            markUpdate();
            return;
        }

        for (ObjectId folder : folders) {
            if (folder != null) attachFolder(folder);
        }
    }

    public void setFolders(String folderIdsString) {
        this.folders = null;
        if (StringUtils.isEmpty(folderIdsString)) {
            markUpdate();
            return;
        }

        String[] split = StringUtils.split(folderIdsString, '/');
        for (String idString : split) {
            attachFolder(ObjectId.valueOf(idString));
        }
    }

    public boolean hasFolders() {
        return folders != null;
    }

    public boolean hasFolders(ObjectId... folders) {
        return this.folders != null && this.folders.containsAll(Arrays.asList(folders));
    }

    public void attachFolder(ObjectId folderId) {
        if (folders == null) {
            folders = new CopyOnWriteArraySet<ObjectId>();
        }
        if (!folders.add(folderId)) {
            throw new IllegalOperationException("Tried to attach an already attached folder");
        }
        markUpdate();
    }

    public void detachFolder(ObjectId folderId) {
        if (!folders.remove(folderId)) {
            throw new IllegalOperationException("Tried to detach a not attached folder");
        }
        if (folders.size() == 0) {
            folders = null;
        }
        markUpdate();
    }

    public Task copy() {
        Task clone;
        try {
            clone = (Task) super.clone();
        }
        catch (CloneNotSupportedException e) {
            throw new IllegalStateException();
        }

        if (hasFolders()) {
            // we have to clone the set but not its items since they are immutable
            clone.folders = new CopyOnWriteArraySet<ObjectId>(folders);
        }
        return clone;
    }

    public static Task create(ObjectId id) {
        Task task = new Task();
        task.setId(id);
        return task;
    }

}
